﻿<%@ WebHandler Language="C#" Class="AHMIDEAF01" %>

using System;
using System.Web;
using System.Linq;

public class AHMIDEAF01 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";
        AjaxResponse axresp = new AjaxResponse();

        if (AHMIDEAFunctions.ContextDomain(context) != "SYSTEM")
        {
            axresp.Status = "0";
            axresp.Message = "Sorry, this feature is not available in current domain.";
        }
        else
        {

            // Field Names
            string f_pass_old = "pass_old";
            string f_pass_new = "pass_new";
            string f_pass_newconf = "pass_newconf";

            // Field valuess
            string txtOldPass = AHMIDEAFunctions.ContextPostData(context, f_pass_old);
            string txtNewPass = AHMIDEAFunctions.ContextPostData(context, f_pass_new);
            string txtNewPassConfirm = AHMIDEAFunctions.ContextPostData(context, f_pass_newconf);

            // validations
            FormValidation validation = new FormValidation();
            validation.RegisterField(f_pass_old, "Old Password", txtOldPass, "Required,LimitLength", 50);
            validation.RegisterField(f_pass_new, "New Password", txtNewPass, "Required,LimitLength", 50);
            validation.RegisterField(f_pass_newconf, "New Password Confirmation", txtNewPassConfirm, "Required,LimitLength", 50);
            validation.ValidateFields();

            if (txtNewPass != txtNewPassConfirm)
            {
                validation.AddCustomError(f_pass_newconf, "Your new password confirmation doesn't match. Please try again.");
            }

            if (validation.IsValid)
            {
                string usr = AHMIDEAFunctions.ContextUser(context);
                using (DC_AHMIDEADataContext dc = new DC_AHMIDEADataContext())
                {
                    SPAHMIDEA_UserAuthenticateResult res = dc.SPAHMIDEA_UserAuthenticate(usr, txtOldPass).FirstOrDefault();
                    if (res != null)
                    {
                        dc.SPAHMIDEA_ChangePassword(AHMIDEAFunctions.ContextUser(context), txtNewPass);
                        axresp.SetStatus(validation, "Your password is successfully updated.");
                    }
                    else
                    {
                        validation.AddCustomError(f_pass_old, "Your old password is incorrect.");
                        axresp.SetStatus(validation);
                    }
                }
            }
            else
            {
                axresp.SetStatus(validation);
            }
        }
        
        context.Response.Write(axresp.GenerateJSON());
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}